// 实现方式2：tsx的方式代替vue的template的单文件方式

import { defineComponent, ref, computed, Fragment } from 'vue'
import  type { PropType } from 'vue'
import type { Placement, Options } from '@popperjs/core'
import type { MenuOption } from './types'
import Tooltip from '../Tooltip/Tooltip.vue'
import type { TooltipInstance } from '../Tooltip/types'

export default defineComponent({
  name: 'GemsDropdown',
  props: {
    placement: {
      type: String as PropType<Placement>,
      default: 'bottom'
    },
    trigger: {
      type: String as PropType<'hover' | 'click'>,
      default: 'hover'
    },
    transition: {
      type: String,
      default: 'fade'
    },
    openDelay: {
      type: Number,
      default: 0
    },
    closeDelay: {
      type: Number,
      default: 0,
    },
    options: {
      type: Object as PropType<Options>,
    },
    menuOptions: {
      type: Array as PropType<MenuOption[]>,
      required: true
    },
    hideAfterClick: {
      type: Boolean,
      default: true
    },
    manual: {
      type: Boolean
    }
  },
  emits: ['visible-change', 'item-click'],
  setup(props, { slots, emit, expose }) {
    const tooltipRef =  ref<TooltipInstance | null>(null)
    const visibleChange = (visible: boolean) => {
      emit('visible-change', visible)
    }
    const itemClick = (item: MenuOption) => {
      if (item.disabled) return
      emit('item-click', item)
      if (props.hideAfterClick) {
        tooltipRef.value?.hide()
      }
    }
    // 选项列表
    const options = computed(() => {
      // 处理 template 中的 v-for
      return props.menuOptions.map(item => {
        return (
          // 空节点
          <Fragment key={item.key}>
            {/* v-if 渲染改写 */}
            {item.divided ? <li role="separator" class="devided-placeholder"></li> : ''}
            <li 
              class={{'gems-dropdown__item': true, 'is-disabled': item.disabled, 'is-divided': item.divided}}
              id={`dropdown-item-${item.key}`}
              onClick={() => itemClick(item)}
            >
              {item.label}
            </li>
          </Fragment>
        )
      })
    })
    expose({
      show: () => tooltipRef.value?.show(),
      hide: () => tooltipRef.value?.hide()
    })
    return () => (
      <div
        class="gems-dropdown"
      >
        <Tooltip 
          trigger={props.trigger} 
          placement={props.placement}
          popperOptions={props.options}
          openDelay={props.openDelay}
          closeDelay={props.closeDelay}
          manual={props.manual}
          ref={tooltipRef}
          onVisible-change={visibleChange}
        >
          {{
            // 默认插槽
            default: () => slots.default && slots.default(),
            // 具名插槽
            content: () => (
              <ul class="gems-dropdown__menu">
                { options.value }
              </ul>
            )
          }}
        </Tooltip>
      </div>
    )
  }
})